package app

import (
	"bookkeeping-gin/app/common/request"
	"bookkeeping-gin/app/common/response"
	"bookkeeping-gin/app/service"
	"bookkeeping-gin/utils"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"log"
)

// CreateTag godoc
//
//	@Summary		CreateTag
//	@Description	CreateTag by tag_name tag_symbol
//	@Tags			Tag
//	@Accept			json
//	@Produce		json
//	@Param			form	body		request.TagForm	true	"TagForm"
//	@Success		200		{object}	service.TokenOutPut
//	@Router			/tag/create [post]
func CreateTag(c *gin.Context) {
	userid, err := utils.GetUseridFromCtx(c)
	if err != nil {
		response.BusinessFail(c, err.Error())
		return
	}
	var form request.TagForm
	if err := c.ShouldBindJSON(&form); err != nil {
		log.Println("CreateTag err:", err)
		response.ValidateFail(c, request.GetErrorMsg(form, err))
		return
	}
	form.CreatedBy = userid
	if err, tag := service.TagService.CreateTag(form); err != nil {
		response.BusinessFail(c, err.Error())
	} else {
		response.Success(c, tag)
	}
}

// DeleteTag Login godoc
//
//	@Summary		Login
//	@Description	Login
//	@Tags			User
//	@Accept			json
//	@Produce		json
//	@Param			form	body		request.LoginForm	true	"LoginForm"
//	@Success		200		{object}	model.User
//	@Router			/user/login [post]
func DeleteTag(c *gin.Context) {
	var form request.LoginForm
	if err := c.ShouldBindJSON(&form); err != nil {
		log.Println("Login err:", err)
		response.ValidateFail(c, request.GetErrorMsg(form, err))
		return
	}

	if err, user := service.UserService.Login(form); err != nil {
		response.BusinessFail(c, err.Error())
	} else {
		tokenData, err, _ := service.JwtService.CreateToken(service.AppGuardName, user)
		if err != nil {
			response.BusinessFail(c, err.Error())
			return
		}
		response.Success(c, tokenData)
	}
}

// EditTag godoc
//
//	@Security		JWT
//	@Summary		Logout
//	@Description	Logout
//	@Tags			User
//	@Accept			json
//	@Produce		json
//	@Security		ApiKeyAuth
//	@Success		200
//	@Router			/user/logout [post]
func EditTag(c *gin.Context) {
	err := service.JwtService.JoinBlackList(c.Keys["token"].(*jwt.Token))
	if err != nil {
		response.BusinessFail(c, "登出失败")
		return
	}
	response.Success(c, "登出成功")
}

// GetMeInfo godoc
//
//	@Security		JWT
//	@Summary		Get current user info
//	@Description	Get user info by ID
//	@Tags			User
//	@Accept			json
//	@Produce		json
//	@Success		200	{object}	model.User
//	@Router			/user/me [get]
func GetTagList(c *gin.Context) {
	if err, user := service.UserService.GetUserInfoById(c.Keys["userid"].(string)); err != nil {
		response.BusinessFail(c, err.Error())
	} else {
		response.Success(c, user)
	}
}
